package com.guochaojava.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.guochaojava.dao.MemberMapper;
import com.guochaojava.dao.RecordDetailMapper;
import com.guochaojava.dao.RecordMapper;
import com.guochaojava.model.Member;
import com.guochaojava.model.Record;
import com.guochaojava.model.RecordDetail;
import com.guochaojava.model.enums.MemberStatusEnum;
import com.guochaojava.model.enums.RecordStatusEnum;
import com.guochaojava.param.GameEndParam;
import com.guochaojava.service.RecordService;
import com.guochaojava.util.ELOResult;
import com.guochaojava.util.ELOUtils;
import com.guochaojava.util.TemplateUtils;
import com.guochaojava.websocket.MyHandler;
import com.lgd.winter.wechat.core.WeChatTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.TextMessage;

import java.util.*;

/**
 * 比赛记录实现接口
 *
 * @author guochao
 * @since 1.0.0
 */
@Service
public class RecordServiceImpl implements RecordService {

    @Autowired
    private RecordMapper dao;
    @Autowired
    private RecordDetailMapper recordDetailDao;
    @Autowired
    private MemberMapper memberDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private WeChatTemplate weChatTemplate;

    @Override
    public int deleteByPrimaryKey(Integer id) {
        return dao.deleteByPrimaryKey(id);
    }

    @Override
    public int insertSelective(GameEndParam param) {
        Record record = new Record();
        BeanUtils.copyProperties(param, record);
        record.setPlayTime(DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
        int result = dao.insertSelective(record);
        List<RecordDetail> recordDetailList = new ArrayList<>();
        if (param.getOne() != null) {
            String[] tem = param.getOne().split("\\,");
            RecordDetail recordDetail = new RecordDetail();
            recordDetail.setNumber(1);
            recordDetail.setRecordId(record.getId());
            recordDetail.setMyScore(Integer.valueOf(tem[0]));
            recordDetail.setRivalScore(Integer.valueOf(tem[1]));
            recordDetail.setType(Integer.valueOf(tem[2]));
            recordDetailList.add(recordDetail);
        }
        if (param.getTwo() != null) {
            String[] tem = param.getTwo().split("\\,");
            RecordDetail recordDetail = new RecordDetail();
            recordDetail.setNumber(2);
            recordDetail.setRecordId(record.getId());
            recordDetail.setMyScore(Integer.valueOf(tem[0]));
            recordDetail.setRivalScore(Integer.valueOf(tem[1]));
            recordDetail.setType(Integer.valueOf(tem[2]));
            recordDetailList.add(recordDetail);
        }
        if (param.getThree() != null) {
            String[] tem = param.getThree().split("\\,");
            RecordDetail recordDetail = new RecordDetail();
            recordDetail.setNumber(3);
            recordDetail.setRecordId(record.getId());
            recordDetail.setMyScore(Integer.valueOf(tem[0]));
            recordDetail.setRivalScore(Integer.valueOf(tem[1]));
            recordDetail.setType(Integer.valueOf(tem[2]));
            recordDetailList.add(recordDetail);
        }
        recordDetailDao.insertList(recordDetailList);

        //websocket
        MyHandler myHandler = new MyHandler();
        myHandler.sendMessageToUser(record.getRivalMemberId().toString(), new TextMessage("red"));

        return result;
    }

    @Override
    public Record selectByPrimaryKey(Integer id) {
        return dao.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(Record record) {
        return dao.updateByPrimaryKeySelective(record);
    }

    @Override
    public int affirm(Integer id, String formId) {
        //更新状态
        Record record = dao.selectByPrimaryKey(id);
        if (!record.getStatus().equals(RecordStatusEnum.AFFIRM.getCode())) {
            record.setStatus(RecordStatusEnum.AFFIRM.getCode());
            dao.updateByPrimaryKeySelective(record);
            //记录分数

            ELOResult r = ELOUtils.rating(record.getScore(), record.getRivalScore(), record.getType(), 32, true);
            Member member = new Member();
            member.setId(record.getMemberId());
            member.setScore(r.getRa());
            member.setStatus(MemberStatusEnum.NORMAL.getCode());
            memberDao.updateByPrimaryKeySelective(member);
            Member rivalMember = new Member();
            rivalMember.setId(record.getRivalMemberId());
            rivalMember.setScore(r.getRb());
            member.setStatus(MemberStatusEnum.NORMAL.getCode());
            memberDao.updateByPrimaryKeySelective(rivalMember);

            //模版消息
            try {
                Map<String, String> map = new HashMap<>(4);
                map.put("keyword1", DateUtil.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
                if (record.getType() == 1) {
                    map.put("keyword2", record.getRivalNickName());
                } else {
                    map.put("keyword2", record.getNickName());
                }

                map.put("keyword3", "您有新的比赛需要确认");
                TemplateUtils.miniPush(weChatTemplate, redisTemplate, record.getRivalOpenId(), formId, "pages/index/index", "HBciVG7YEYAucH4dtUkZJ0EUYeXKGXBMUw6QGj0S8rY", map);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return 1;
    }

    @Override
    public Record read(Integer id) {
        Record record = new Record();
        record.setId(id);
        record.setStatus(RecordStatusEnum.READ.getCode());
        dao.updateByPrimaryKeySelective(record);
        return dao.read(id);
    }

    @Override
    public List<Record> selectByRivalId(Integer id) {
        List<Record> list = dao.selectByRivalId(id);
        DateTime nowTime = new DateTime(new Date());
        int nowDay = nowTime.dayOfMonth();

        List<Record> dateList = new ArrayList<>();
        for (Record record : list) {
            String playTime = record.getPlayTime();
            DateTime time = DateUtil.parse(playTime);

            int hour = time.hour(false);
       /*     String hourStr = hour + "";
            if (hour < 10) {
                hourStr = "0" + hourStr;
            }*/
            int minute = time.minute();
            String minuteStr = minute + "";
            if (minute < 10) {
                minuteStr = "0" + minuteStr;
            }
            if (nowDay == DateUtil.parse(playTime).dayOfMonth()) {
                record.setPlayTime(getAmOrPm(playTime) + " " + hour + ":" + minuteStr);
            } else {
                record.setPlayTime(time.month() + 1 + "月" + time.dayOfMonth() + "日 " + getAmOrPm(playTime) + " " + hour + ":" + minuteStr);
            }
            dateList.add(record);
        }
        return dateList;
    }

    @Override
    public PageInfo<Record> myRecord(Integer id, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Record> list = dao.myRecord(id);
        DateTime nowTime = new DateTime(new Date());
        int nowDay = nowTime.dayOfMonth();

        List<Record> dateList = new ArrayList<>();
        for (Record record : list) {
            String playTime = record.getPlayTime();
            DateTime time = DateUtil.parse(playTime);

            int hour = time.hour(false);
       /*     String hourStr = hour + "";
            if (hour < 10) {
                hourStr = "0" + hourStr;
            }*/
            int minute = time.minute();
            String minuteStr = minute + "";
            if (minute < 10) {
                minuteStr = "0" + minuteStr;
            }
            if (nowDay == DateUtil.parse(playTime).dayOfMonth()) {
                record.setPlayTime(getAmOrPm(playTime) + " " + hour + ":" + minuteStr);
            } else {
                record.setPlayTime(time.month() + 1 + "月" + time.dayOfMonth() + "日 " + getAmOrPm(playTime) + " " + hour + ":" + minuteStr);
            }
            dateList.add(record);
        }
        PageInfo<Record> pageInfo = new PageInfo<>(dateList);
        return pageInfo;
    }


    @Override
    public Record selectRivalDetailById(Integer id) {
        Record record =  dao.selectRivalDetailById(id);

        DateTime nowTime = new DateTime(new Date());
        int nowDay = nowTime.dayOfMonth();
        String playTime = record.getPlayTime();
        DateTime time = DateUtil.parse(playTime);

        int hour = time.hour(false);

        int minute = time.minute();
        String minuteStr = minute + "";
        if (minute < 10) {
            minuteStr = "0" + minuteStr;
        }
        if (nowDay == DateUtil.parse(playTime).dayOfMonth()) {
            record.setPlayTime(getAmOrPm(playTime) + " " + hour + ":" + minuteStr);
        } else {
            record.setPlayTime(time.month() + 1 + "月" + time.dayOfMonth() + "日 " + getAmOrPm(playTime) + " " + hour + ":" + minuteStr);
        }

        return record;
    }

    private String getAmOrPm(String time) {
        DateTime dateTime = DateUtil.parse(time);
        if (dateTime.hour(true) < 12) {
            return "上午";
        } else {
            return "下午";
        }
    }

    @Override
    public boolean readFlag(Integer id) {
        List<Record> records = dao.readFlag(id);
        if (records.size() > 0) {
            return true;
        }
        return false;
    }

    private List<Record> page(List<Record> myRecord, Integer pageNum, Integer pageSize) {
        int size = myRecord.size();
        if (pageNum * pageNum > size) {
            return new ArrayList<>();
        } else {

            return myRecord;
        }
    }
}